package com.fire.web.modules.all.controller;

import com.fire.common.mybatis.mvc.wrapper.EntityWrapper;
import com.fire.web.modules.all.constant.ErrorCodeConstants;
import com.fire.web.modules.all.entity.*;
import com.fire.web.modules.all.request.DispelAlertDTO;
import com.fire.web.modules.all.response.AlertResp;
import com.fire.web.modules.all.service.*;
import com.fire.web.modules.all.utils.TokenUtil;
import com.fire.web.modules.sso.service.IOAuthService;
import com.fire.web.security.shiro.realm.UserRealm;
import com.smartthing.rest.model.device.Site;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("/alert")
public class AlertController {
	private static final Logger LOGGER = LoggerFactory.getLogger(AlertController.class);
	@Autowired
	ITMitErrorCodeService errorCodeService;
	@Autowired
	IAllUserService allUserService;
	@Autowired
	private SolrClient client;
	@Autowired
	IOAuthService oAuthService;
	@Autowired
	IFireProprietorService fireProprietorService;
	@Autowired
	IFireSupervisorService fireSupervisorService;
	@Autowired
	IFireMaintainorService fireMaintainorService;
	@Autowired
	ISiteService siteService;
	@Autowired
	IRecordAlarmService recordAlarmService;
	@Value("${spring.data.solr.core}")
	String core;

	/**
	 * 查询消防资产事件链表
	 *
	 * @return
	 * @author zengzhengfu
	 */
	@PostMapping(value = "/dispelalert")
	@ResponseBody
	public AjaxResult dispelalert(@Validated DispelAlertDTO dispelAlertDTO, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {
		if (bindingResult.hasErrors()) {
			for (FieldError fieldError : bindingResult.getFieldErrors()) {
				String message = fieldError.getDefaultMessage();
				LOGGER.error(message);
				return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "参数有误," + message, "参数有误," + message);
			}
		}

		String token = TokenUtil.getToken(request, response);
		UserRealm.Principal principalByAccessToken = oAuthService.getPrincipalByAccessToken(token);
		String username = principalByAccessToken.getUsername();

		String alertid = dispelAlertDTO.getAlertid();
		try {
			SolrQuery params = new SolrQuery();
			//查询条件
			params.set("q", "eventId:" + alertid);

			//yml文件未配置具体的collection，所以此处需要配置
			QueryResponse queryResponse = client.query(core, params);

			SolrDocumentList results = queryResponse.getResults();
			SolrDocument entries = results.get(0);
			//入库
			RecordAlarmModel recordAlarmModel = new RecordAlarmModel();
			recordAlarmModel.setAlertid((String) entries.get("eventId"));
			recordAlarmModel.setEventType("Alert");
			recordAlarmModel.setDeviceAssignmentToken((String) entries.get("assignmentToken"));
			recordAlarmModel.setDeviceAssignmentType((String) entries.get("assignmentType"));
			recordAlarmModel.setAssetId((String) entries.get("assetId"));
			recordAlarmModel.setSiteToken((String) entries.get("siteToken"));
			recordAlarmModel.setEventDate((Date) entries.get("eventDate"));
			recordAlarmModel.setReceivedDate((Date) entries.get("receivedDate"));
			List alertType = (List) entries.get("alertType");
			recordAlarmModel.setType(alertType.toString());
			recordAlarmModel.setMessage((String) entries.get("alertMessage"));
			recordAlarmModel.setLevel((String) entries.get("alertLevel"));
			recordAlarmModel.setSource((String) entries.get("alertSource"));
			recordAlarmModel.setCreatetime(new Date());
			recordAlarmModel.setOperattime(new Date());
			recordAlarmModel.setOperator(username);
			recordAlarmModel.setSpotimage(dispelAlertDTO.getSpotimage());
			recordAlarmModel.setReason(dispelAlertDTO.getReason());

			recordAlarmService.insert(recordAlarmModel);
			//删除记录
			client.deleteById(core, alertid);
			client.commit(core);
			return new AjaxResult(ErrorCodeConstants.SUCCESS, "消除成功", "消除成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AjaxResult(ErrorCodeConstants.SUCCESS, "消除失败", "消除失败");
	}

	/**
	 * 查询告警
	 *
	 * @param
	 * @return
	 */
	@GetMapping(value = "/getAlertList")
	@ResponseBody
	public AjaxResult getAlert(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {

		AjaxResult ajaxResult = new AjaxResult();

		try {
			String token = TokenUtil.getToken(request, response);
			UserRealm.Principal principalByAccessToken = oAuthService.getPrincipalByAccessToken(token);
			String adminid = principalByAccessToken.getId();

			Integer page = Integer.parseInt((String) params.get("page"));
			Integer limit = Integer.parseInt((String) params.get("limit"));
			//Date startdate = (Date)params.get("startdate");
			//Date enddate = (Date)params.get("enddate");
			String role = (String) params.get("role");
			List<String> siteTokenList = getSiteTokenList(adminid, role);
			if (siteTokenList.size() == 0) {
				return new AjaxResult(ErrorCodeConstants.SITE_IS_NOT_EXIST, "站点未关联", "站点未关联");
			}

			SolrQuery sol_params = new SolrQuery();
			//多条件查询
			StringBuilder multi_params = new StringBuilder("meta.range:" + params.get("range"));
			multi_params.append(" AND eventType:Alert");

			for (int i = 0; i < siteTokenList.size(); i++) {
				if (siteTokenList.size() == 1) {
					multi_params.append(" AND siteToken:" + siteTokenList.get(i));
					break;
				}
				if (i == 0) {
					multi_params.append(" AND siteToken:(" + siteTokenList.get(i));
				} else if (i == siteTokenList.size() - 1) {
					multi_params.append(" OR " + siteTokenList.get(i) + ")");
				} else {
					multi_params.append(" OR " + siteTokenList.get(i));
				}
			}

			if (page != null && limit != null) {
				sol_params.setStart(page - 1);
				sol_params.setRows(limit);
			}

			//yml文件未配置具体的collection，所以此处需要配置
			sol_params.setQuery(multi_params.toString());

			LOGGER.info("solr查询语句：" + sol_params.toString());
			QueryResponse queryResponse = client.query(core, sol_params);

			SolrDocumentList results = queryResponse.getResults();
			List records = new ArrayList();
			for (SolrDocument document : results) {
				AlertResp alert = new AlertResp();
				alert.setEventId((String) document.get("eventId"));
				alert.setAssignmentToken((String) document.get("assignmentToken"));
				alert.setAssignmentType((String) document.get("assignmentType"));
				alert.setAssetId((String) document.get("assetId"));
				alert.setSiteToken((String) document.get("siteToken"));
				alert.setEventDate((Date) document.get("eventDate"));
				alert.setReceivedDate((Date) document.get("receivedDate"));

				alert.setAlertType(document.get("alertType").toString());
				alert.setAlertMessage((String) document.get("alertMessage"));
				alert.setAlertLevel((String) document.get("alertLevel"));
				alert.setAlertSource((String) document.get("alertSource"));
				Map meta = getmetadata(document, "meta");
				alert.setMetadata(meta);
				records.add(alert);
			}
			Map result = new HashMap();
			result.put("total", records.size());
			result.put("records", records);
			ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS, "获取成功", result, "获取成功");
		} catch (Exception e) {
			LOGGER.error("AlertController.getAlert().error  错误为：", e);
			ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
		}
		//替换tips
		ajaxResult = replaceTips(ajaxResult);
		return ajaxResult;
	}

	private List<String> getSiteTokenList(String adminid, String role) {
		List siteTokenList = new ArrayList();
		List<SiteModel> siteList = new ArrayList();
		switch (role) {
			case "proprietor":
				FireProprietorModel fireProprietorModel = fireProprietorService.selectOne(new EntityWrapper<FireProprietorModel>().eq("adminid", adminid));
				siteList = siteService.selectList(new EntityWrapper<SiteModel>().eq("proprietor", fireProprietorModel.getProprietor()));
				break;
			case "supervisor":
				FireSupervisorModel fireSupervisorModel = fireSupervisorService.selectOne(new EntityWrapper<FireSupervisorModel>().eq("adminid", adminid));
				siteList = siteService.selectList(new EntityWrapper<SiteModel>().eq("supervisorid", fireSupervisorModel.getSupervisorid()));
				break;
			case "maintainor":
				FireMaintainorModel fireMaintainorModel = fireMaintainorService.selectOne(new EntityWrapper<FireMaintainorModel>().eq("adminid", adminid));
				siteList = siteService.selectList(new EntityWrapper<SiteModel>().eq("maintainor", fireMaintainorModel.getMaintainor()));
				break;
		}
		for (SiteModel site : siteList) {
			siteTokenList.add(site.getSitetoken());
		}
		return siteTokenList;
	}

	private Map getmetadata(SolrDocument document, String meta) {
		Map result = new HashMap();
		for (Map.Entry<String, Object> entry : document) {
			if (entry.getKey().contains(meta)) {
				result.put(entry.getKey().replace(meta + ".", ""), entry.getValue());
			}
		}
		return result;
	}

	protected AjaxResult replaceTips(AjaxResult ajaxResult) {
		String tips = errorCodeService.getTips(ajaxResult.getStatus());
		if (StringUtils.isNotBlank(tips)) {
			ajaxResult.setTips("[" + ajaxResult.getStatus() + "]" + tips);
		} else {
			ajaxResult.setTips("[" + ajaxResult.getStatus() + "]" + ajaxResult.getTips());
		}
		return ajaxResult;
	}
}
